<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-900 via-gray-900 to-black flex items-center justify-center py-12">
    <!-- 背景装饰 -->
    <div class="absolute inset-0 overflow-hidden">
      <div
        class="absolute -top-1/2 -left-1/2 w-full h-full bg-gradient-to-br from-yellow-500/10 to-orange-500/10 rounded-full blur-3xl"
      ></div>
      <div
        class="absolute -bottom-1/2 -right-1/2 w-full h-full bg-gradient-to-tl from-orange-500/10 to-amber-600/10 rounded-full blur-3xl"
      ></div>
    </div>

    <div class="relative w-full max-w-md mx-auto px-6">
      <!-- 注册表单 -->
      <div class="bg-white/5 backdrop-blur-lg border border-white/10 rounded-2xl p-6 shadow-2xl">
        <h2 class="text-2xl font-bold text-white text-center mb-4">创建账户</h2>

        <!-- 注册福利提示 - 更紧凑 -->
        <div class="mb-6 bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border border-yellow-500/20 rounded-lg p-3">
          <div class="flex items-center space-x-2 text-yellow-400">
            <i class="i-carbon-gift text-lg"></i>
            <div class="text-sm">
              <span class="font-semibold">新用户福利：</span>
              <span class="text-gray-300">注册送3天VIP，查看全部比赛分析</span>
            </div>
          </div>
        </div>

        <form @submit.prevent="handleRegister" class="space-y-4">
          <!-- 用户名 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 用户名 </label>
            <div class="relative">
              <input
                v-model="registerForm.username"
                type="text"
                required
                placeholder="请输入用户名"
                maxlength="20"
                autocomplete="off"
                class="w-full px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors"
              />
              <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
                <i class="i-carbon-user text-gray-400"></i>
              </div>
            </div>
          </div>

          <!-- 邮箱 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 邮箱地址 </label>
            <div class="relative">
              <input
                v-model="registerForm.email"
                type="email"
                required
                placeholder="请输入邮箱地址"
                maxlength="30"
                autocomplete="off"
                class="w-full px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors"
              />
              <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
                <i class="i-carbon-email text-gray-400"></i>
              </div>
            </div>
          </div>

          <!-- 验证码 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 邮箱验证码 </label>
            <div class="flex space-x-3">
              <input
                v-model="registerForm.verifyCode"
                type="text"
                required
                placeholder="请输入验证码"
                maxlength="6"
                autocomplete="off"
                class="flex-1 px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors"
              />
              <CButton :loading="sendVerifyCodeLoading" :disabled="countdown > 0 || !canSendCode" @click="sendVerifyCode">
                <span v-if="countdown > 0">{{ countdown }}s</span>
                <span v-else>获取验证码</span>
              </CButton>
            </div>
          </div>

          <!-- 密码 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 密码 </label>
            <div class="relative">
              <input
                v-model="registerForm.password"
                :type="showPassword ? 'text' : 'password'"
                required
                placeholder="请输入密码"
                maxlength="30"
                autocomplete="new-password"
                class="w-full px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors pr-10"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="bg-white/5 absolute inset-y-0 right-0 px-2 flex items-center"
              >
                <img v-if="showPassword" src="/assets/image/open-eyes.svg" class="w-4 h-4" />
                <img v-else src="/assets/image/close-eyes.svg" class="w-4 h-4" />
              </button>
            </div>
            <!-- 简化密码强度指示 -->
            <div v-if="registerForm.password" class="mt-1 flex items-center space-x-2">
              <div class="flex space-x-1">
                <div
                  v-for="i in 4"
                  :key="i"
                  class="h-1 w-4 rounded-full transition-colors"
                  :class="passwordStrength >= i ? getStrengthColor(passwordStrength) : 'bg-gray-500'"
                ></div>
              </div>
              <div class="text-xs" :class="getStrengthTextColor(passwordStrength)">
                {{ getStrengthText(passwordStrength) }}
              </div>
            </div>
          </div>

          <!-- 确认密码 -->
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-1"> 确认密码 </label>
            <div class="relative">
              <input
                v-model="registerForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                required
                placeholder="请再次输入密码"
                maxlength="30"
                autocomplete="new-password"
                class="w-full px-4 py-2.5 bg-white/5 border border-white/20 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 focus:ring-1 focus:ring-yellow-500 transition-colors pr-10"
              />
              <button
                type="button"
                @click="showConfirmPassword = !showConfirmPassword"
                class="bg-white/5 absolute inset-y-0 right-0 px-2 flex items-center"
              >
                <img v-if="showConfirmPassword" src="/assets/image/open-eyes.svg" class="w-4 h-4" />
                <img v-else src="/assets/image/close-eyes.svg" class="w-4 h-4" />
              </button>
            </div>
            <div
              v-if="registerForm.confirmPassword && registerForm.password !== registerForm.confirmPassword"
              class="text-red-400 text-xs mt-1"
            >
              密码不一致
            </div>
          </div>

          <!-- 服务条款 -->
          <div class="flex items-start space-x-2 pt-2">
            <input
              v-model="registerForm.agreeTerms"
              type="checkbox"
              required
              class="w-4 h-4 mt-0.5 text-blue-600 bg-transparent border border-gray-600 rounded cursor-pointer"
            />
            <span class="text-xs text-gray-300 leading-relaxed">
              我已阅读并同意
              <a href="/user-agreement" class="text-yellow-400 hover:text-yellow-300">《用户协议》</a>
              和
              <a href="/privacy-policy" class="text-yellow-400 hover:text-yellow-300">《隐私政策》</a>
            </span>
          </div>

          <!-- 注册按钮 -->
          <CButton
            type="submit"
            :disabled="isLoading || !isFormValid"
            :class="[
              'w-full py-2.5 px-4 text-white font-semibold rounded-lg transition-all duration-300 transform cursor-pointer',
              isFormValid && !isLoading
                ? 'bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-600 hover:to-orange-600 '
                : 'bg-gray-500 opacity-50 cursor-not-allowed transform-none',
            ]"
          >
            <span v-if="isLoading" class="flex items-center justify-center">
              <div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
              注册中...
            </span>
            <span v-else>立即注册</span>
          </CButton>
        </form>

        <!-- 登录链接 -->
        <div class="mt-6 text-center">
          <span class="text-gray-400 text-sm">已有账户？</span>
          <NuxtLink to="/login" class="text-yellow-400 hover:text-yellow-300 font-medium ml-1 transition-colors text-sm">
            立即登录
          </NuxtLink>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref, reactive, computed } from 'vue';
import { queryRegister, querySendVerifyCode } from '~/apis/auth';

// SEO配置
useSEO({
  title: '注册 - 球球助手',
  description: '注册球球助手账户，享受专业的足球数据查询服务，新用户注册即送3天VIP会员',
  keywords: '注册,用户注册,球球助手,足球数据,免费VIP',
});

// 防止已登录用户访问注册页
definePageMeta({ layout: 'auth' });

// 响应式数据
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const isLoading = ref(false);
const countdown = ref(0);

const registerForm = reactive({
  username: '',
  email: '',
  verifyCode: '',
  password: '',
  confirmPassword: '',
  agreeTerms: false,
});
// const registerForm = reactive({
//   username: 'admin',
//   email: '15360001247@163.com',
//   verifyCode: '123456',
//   password: '123456mzp',
//   confirmPassword: '123456mzp',
//   agreeTerms: true,
// });

// 密码强度计算
const passwordStrength = computed(() => {
  const password = registerForm.password;
  if (!password) return 0;

  let strength = 0;
  if (password.length >= 6) strength++;
  if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
  if (/\d/.test(password)) strength++;
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;

  return strength;
});

// 发送验证码按钮是否可用
const canSendCode = computed(() => {
  return registerForm.email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email);
});

// 表单验证 - 修正字段
const isFormValid = computed(() => {
  return (
    registerForm.username &&
    registerForm.email &&
    registerForm.verifyCode &&
    registerForm.password &&
    registerForm.confirmPassword &&
    registerForm.password === registerForm.confirmPassword &&
    registerForm.agreeTerms
  );
});

// 密码强度相关方法
const getStrengthColor = (strength: number) => {
  switch (strength) {
    case 1:
      return 'bg-red-500';
    case 2:
      return 'bg-yellow-500';
    case 3:
      return 'bg-blue-500';
    case 4:
      return 'bg-green-500';
    default:
      return 'bg-gray-500';
  }
};

const getStrengthTextColor = (strength: number) => {
  switch (strength) {
    case 1:
      return 'text-red-400';
    case 2:
      return 'text-yellow-400';
    case 3:
      return 'text-blue-400';
    case 4:
      return 'text-green-400';
    default:
      return 'text-gray-400';
  }
};

const getStrengthText = (strength: number) => {
  switch (strength) {
    case 1:
      return '密码强度：弱';
    case 2:
      return '密码强度：一般';
    case 3:
      return '密码强度：良好';
    case 4:
      return '密码强度：很强';
    default:
      return '请输入密码';
  }
};

const userStore = useUserStore();
const sendVerifyCodeLoading = ref(false);

// 1) 发送验证码
const sendVerifyCode = async () => {
  // 1 发送验证码
  sendVerifyCodeLoading.value = true;
  await querySendVerifyCode({ email: registerForm.email }).finally(() => (sendVerifyCodeLoading.value = false));
  // 2 开始倒计时
  countdown.value = 120;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) clearInterval(timer);
  }, 1000);
  // 3 提示用户
  ElMessage.success('验证码发送成功，请注意查收');
};
// 2) 注册
const handleRegister = async () => {
  if (!isFormValid.value) return;
  isLoading.value = true;
  try {
    const res = await queryRegister({
      username: registerForm.username,
      email: registerForm.email,
      validCode: registerForm.verifyCode,
      password: registerForm.password,
    });
    userStore.onRegister(res.data);
    navigateTo('/');
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  if (userStore.isLoggedIn) navigateTo('/');
});
</script>
